﻿#if ENABLE_SDKUTIL_WX && !UNITY_EDITOR
#define ENABLE_SDKUTIL_WX2
#endif

using cframework.SDKUtil;
using System.Collections;
using UnityEngine;
using wnity.zframework;

#if ENABLE_SDKUTIL_WX2
using WeChatWASM;
#endif

public class WxAd : MonoBehaviour
{
    public string adUnitId;
    public bool autoInit = true;

    //IEnumerator InitAd()
    //{
    //    if (string.IsNullOrEmpty(adUnitId))
    //    {
    //        Debug.LogError("adUnitId is null");
    //        yield break;
    //    }

    //    var w = InitAd(adUnitId).WithResult();
    //    yield return w;
    //    var success = (bool)w.Current;

    //    Debug.Log("InitAd: " + success);

    //    if (success)
    //    {
    //        StartCoroutine(LoadAdLoop());
    //    }
    //}

    //IEnumerator ShowAd()
    //{
    //    var w = ShowAd().WithResult();
    //    yield return w;
    //    var success = (bool)w.Current;

    //    Debug.Log("ShowAd get reward: " + success);
    //}


#if ENABLE_SDKUTIL_WX2

        WXRewardedVideoAd _ad;
        bool adLoaded = false;
    //bool adLoadCallbacked = false;
#endif

    public bool isInited { get; private set; }

    private IEnumerator Start()
    {
        if(autoInit && SDKUtil_WX.instance != null)
        {
            while(!SDKUtil_WX.instance.isInited)
            {
                yield return null;
            }

            if (string.IsNullOrEmpty(adUnitId))
            {
                Debug.LogError("adUnitId is null");
                yield break;
            }

            var w = InitAd().WithResult();
            yield return w;
            var success = (bool)w.Current;

            Debug.Log("InitAd: " + success);

            if (success)
            {
                StartCoroutine(LoadAdLoop());
            }
        }
    }

    public IEnumerator InitAd()
    {
        if(isInited)
        {
            yield return true;
            yield break;
        }

        var success = false;
#if ENABLE_SDKUTIL_WX2
            // ����ʼ��,���Զ���ȡ���һ��
            _ad = WX.CreateRewardedVideoAd(new WXCreateRewardedVideoAdParam
            {
                adUnitId = adUnitId,
            });


            var adLoadCallbacked = false;
            void onLoad(WXADLoadResponse response) //onload�������Զ���ȡ���Ļص�����������ʱ��ȡ��һ����棬����ʾ���ɹ����Զ���ȡ��һ�����
            {
                success = true;
                adLoadCallbacked = true;
                //adLoaded = response.errMsg != null;
            }
            _ad.OnLoad(onLoad);


            void onError(WXADErrorResponse response)
            {
                adLoadCallbacked = true;

                var _adErrorCode = response.errCode;

                Debug.LogError($"ad error: {response.errCode} | {response.errMsg}");

                switch (_adErrorCode)
                {
                    case 0:
                        //if (!_adLoadComplete)
                        //{
                        //    StartLoadAD();//δ��������
                        //                  //_adResult.data = "�����δ׼������";
                        //                  //_adResult.errMsg = "�����δ׼������";
                        //    _adResult.data = "���޹��,��ʹ�÷���";
                        //    _adResult.errMsg = "��������:" + _adErrorCode;
                        //}
                        //else
                        //{
                        //    _adResult.data = "���޹��,��ʹ�÷���";
                        //    _adResult.errMsg = "��������:" + _adErrorCode;
                        //}
                        //_adResult.code = -1;//����������Ϊ0
                        break;
                    case 1000://��˵��ô���
                    case 1003://��˵��ô���
                    case 1004://���ʺϵĹ��
                    case 1005://�����������
                    case 1006://������������
                    case 1007://�����������
                    case 1008://��浥Ԫ�ѹر�
                        //_adResult.data = "���޹��,��ʹ�÷���";
                        //_adResult.errMsg = "��������:" + _adErrorCode;
                        break;
                    case 1001://��������
                    case 1002://id����
                        //Debug.LogError($"����������{_adErrorCode}");
                        //_adResult.data = "���޹��,��ʹ�÷���";
                        //_adResult.errMsg = "��������:" + _adErrorCode;
                        break;
                    case 99999://�Զ���
                        //_adResult.data = "��������ʧ��,�Ժ�����";
                        //_adResult.errMsg = "��������ʧ��,�Ժ�����";
                        break;
                    default://���ڴ�������
                        //_adResult.data = "��������ʧ��,�Ժ�����";
                        //_adResult.errMsg = "��������:" + _adErrorCode;
                        break;
                }
            }
            _ad.OnError(onError);

            yield return new WaitUntil(() => adLoadCallbacked);

            _ad.OffLoad(onLoad);
            _ad.OffError(onError);
#endif
        isInited = success;
        yield return success;
    }

    public IEnumerator ShowAd(string branchId = null, string branchDim = null)
    {
        if(!isInited)
        {
            yield return false;
            yield break;
        }

        var canReward = false;
#if ENABLE_SDKUTIL_WX2
            //yield return new WaitUntil(() => adLoadCallbacked); //�ȴ��Զ���ȡ

            //if(!adLoaded) //�Զ���ȡʧ�ܣ�ֻ���ֶ���ȡ
            //{
            //    var retryCount = 1;
            //    var j = 0;
            //    for (; j < retryCount; j++)
            //    {
            //        var w = LoadAd().WithResult();
            //        yield return w;
            //        var loadSuccess = (bool)w.Current;
            //        if (!loadSuccess)
            //        {
            //            yield return false;
            //            yield break;
            //        }
            //    }
            //}

            var onCloseCallbacked = false;

            void OnClose(WXRewardedVideoAdOnCloseResponse res)
            {
                if (res != null && res.isEnded)
                {
                    // �������Ž����������·���Ϸ����
                    onCloseCallbacked = true;
                    canReward = true;
                }
                else
                {
                    // ������;�˳������·���Ϸ����
                    onCloseCallbacked = true;
                }
            };

            int showRetryCount = 3;
            _ad.OnClose(OnClose);
            for (var i = 0; i < showRetryCount; i++)
            {
                yield return new WaitUntil(() => adLoaded);

                var callbacked = false;
                var showSuccess = false;
                if (branchDim != null && branchId != null)
                {
                    _ad.Show(branchId, branchDim, (response) =>
                    {
                        showSuccess = true;
                        callbacked = true;
                    },
                    (response) =>
                    {
                        callbacked = true;
                    });
                }
                else
                {
                    _ad.Show((response) =>
                    {
                        showSuccess = true;
                        callbacked = true;
                    },
                    (response) =>
                    {
                        callbacked = true;
                    });
                }

                yield return new WaitUntil(() => callbacked);

                if (!showSuccess) //��ʾʧ�ܣ�ֻ���ֶ���ȡ
                {
                    //var retryCount = 1;
                    //var j = 0;
                    //for (; j < retryCount; j++)
                    //{ 
                    //    var w = LoadAd().WithResult();
                    //    yield return w;
                    //    var loadSuccess = (bool)w.Current;
                    //    if(loadSuccess)
                    //    {
                    //        break;
                    //    }
                    //}

                    //if(j == retryCount)
                    //{
                    //    _ad.OffClose(OnClose);
                    //    yield return false;
                    //    yield break;
                    //}

                    adLoaded = false;
                    continue;
                }
                //else //show�ɹ�����Զ���ȡ��һ�����
                //{
                //    adLoadCallbacked = false;
                //    adLoaded = false;
                //}

                yield return new WaitUntil(() => onCloseCallbacked);
                adLoaded = false;

                _ad.OffClose(OnClose);
                yield return canReward;
                yield break;
            }

            _ad.OffClose(OnClose);
#endif
        yield return false;
        yield break;

    }

    public IEnumerator LoadAd()
    {
        var success = false;
#if ENABLE_SDKUTIL_WX2
            var callbacked = false;

            _ad.Load(success: (SuccessRes) =>
                    {
                        callbacked = true;
                        success = true;
                    },
                    failed: (failRes) =>
                    {
                        callbacked = true;
                    });

            yield return new WaitUntil(() => callbacked);
#endif
        yield return success;
    }


    public IEnumerator LoadAdLoop()
    {
#if ENABLE_SDKUTIL_WX2
            while (true)
            {
                yield return new WaitUntil(() => !adLoaded);
                var w = LoadAd().WithResult();
                yield return w;
                var loadSuccess = (bool)w.Current;
                adLoaded = loadSuccess;
            }
#else
        yield return null;
#endif
    }
}
